<template>
  <div class="ai-assistant">
      <div class="ai-avatar-container">
        <div class="message-bubble">
          <div class="bubble-content">
            有什么事情可以跟我聊聊噢~
          </div>
          <div class="bubble-arrow"></div>
        </div>

        <div class="ai-avatar" @click="toggleChat" :class="{ active: showChat }">
          <div class="avatar-body">
            <div class="avatar-face">
              <div class="eyes">
                <div class="eye left"></div>
                <div class="eye right"></div>
              </div>
              <div class="mouth" :class="{ talking: isTyping }"></div>
            </div>
          </div>
          <div class="pulse-ring" v-if="hasNewMessage"></div>
        </div>
    </div>

    <!-- 问答框 -->
    <div class="chat-container" v-show="showChat">
      <div class="chat-header">
        <h3>AI助手</h3>
        <div class="header-actions">
          <el-button size="mini" @click="clearContext" :loading="clearing">清除记忆</el-button>
          <el-button size="mini" icon="el-icon-close" @click="showChat = false"></el-button>
        </div>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(msg, index) in messages" :key="index"
             class="message" :class="msg.type">
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(msg.content)"></div>
            <div class="message-time">{{ msg.time }}</div>
          </div>
        </div>
        <div v-if="isTyping" class="message ai typing">
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <el-input
            v-model="inputMessage"
            placeholder="请输入您的问题..."
            @keyup.enter.native="sendMessage"
            :disabled="isTyping"
            ref="messageInput">
          <el-button slot="append" @click="sendMessage" :disabled="isTyping || !inputMessage.trim()">
            发送
          </el-button>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AIAssistant',
  data() {
    return {
      showChat: false,
      messages: [],
      inputMessage: '',
      isTyping: false,
      clearing: false,
      hasNewMessage: false,
      currentResponse: ''
    }
  },
  computed: {
    userId() {
      return localStorage.getItem('userId') || 'anonymous'
    }
  },
  methods: {
    toggleChat() {
      this.showChat = !this.showChat
      this.hasNewMessage = false
      if (this.showChat) {
        this.$nextTick(() => {
          this.$refs.messageInput.focus()
        })
      }
    },

    async sendMessage() {
      if (!this.inputMessage.trim() || this.isTyping) return

      const userMessage = {
        type: 'user',
        content: this.inputMessage,
        time: this.formatTime(new Date())
      }

      this.messages.push(userMessage)
      const message = this.inputMessage
      this.inputMessage = ''
      this.isTyping = true
      this.currentResponse = ''

      // 创建AI消息占位符
      const aiMessage = {
        type: 'ai',
        content: '',
        time: this.formatTime(new Date())
      }
      this.messages.push(aiMessage)
      this.scrollToBottom()

      try {
        console.log('发送消息:', message)

        const response = await fetch(`/api/ai/chat/${this.userId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ message })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let buffer = ''

        const processStream = async () => {
          while (true) {
            const { done, value } = await reader.read()

            if (done) {
              this.isTyping = false
              break
            }

            const chunk = decoder.decode(value, { stream: true })
            buffer += chunk
            const lines = buffer.split('\n')

            // 保留最后一行（可能不完整）
            buffer = lines.pop() || ''

            // 逐行处理
            for (const line of lines) {
              if (line.startsWith('data:')) {
                const eventData = line.substring(5).trim()

                if (eventData === '') continue
                if (eventData === '[DONE]') {
                  this.isTyping = false
                  return
                }

                // 实时更新内容
                this.currentResponse += eventData
                aiMessage.content = this.currentResponse

                // 强制Vue更新视图
                this.$forceUpdate()

                // 滚动到底部
                await this.$nextTick()
                this.scrollToBottom()

                // 添加小延迟以实现打字机效果
                await new Promise(resolve => setTimeout(resolve, 50))
              }
            }
          }
        }

        await processStream()

      } catch (error) {
        console.error('发送消息失败:', error)
        this.isTyping = false
        aiMessage.content = '抱歉，AI服务暂时不可用，请稍后重试。'
        this.$message.error('发送失败: ' + error.message)
      }
    },

    clearContext() {
      this.clearing = true
      this.$axios.delete(`/api/ai/context/${this.userId}`)
          .then(() => {
            this.messages = []
            this.$message.success('对话记忆已清除')
          })
          .catch(error => {
            console.error('清除上下文失败:', error)
            this.$message.error('清除失败')
          })
          .finally(() => {
            this.clearing = false
          })
    },

    formatMessage(content) {
      return content.replace(/\n/g, '<br>')
    },

    formatTime(date) {
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  },

  mounted() {
    this.messages.push({
      type: 'ai',
      content: '你好！我是AI助手，有什么可以帮助您的吗？',
      time: this.formatTime(new Date())
    })
  }
}
</script>

<style scoped>
.ai-assistant {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.message-bubble {
  position: absolute;
  top: -40px;
  left: -30%;
  transform: translateX(-50%);
  background: white;
  border-radius: 18px;
  padding: 8px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 3;
  animation: bubbleFloat 2s ease-in-out infinite;
}

.bubble-content {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  font-weight: 500;
}

.bubble-arrow {
  position: absolute;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid white;
}

@keyframes bubbleFloat {
  0%, 100% {
    transform: translateX(-50%) translateY(0px);
  }
  50% {
    transform: translateX(-50%) translateY(-3px);
  }
}

.ai-avatar {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  position: relative;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.ai-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}

.ai-avatar.active {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.avatar-body {
  color: white;
  font-size: 24px;
}

.avatar-face {
  position: relative;
}

.eyes {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
}

.eye {
  width: 4px;
  height: 4px;
  background: white;
  border-radius: 50%;
}

.mouth {
  width: 12px;
  height: 6px;
  border: 2px solid white;
  border-top: none;
  border-radius: 0 0 12px 12px;
  margin: 0 auto;
  transition: all 0.3s ease;
}

.mouth.talking {
  animation: talking 0.5s infinite alternate;
}

@keyframes talking {
  0% { transform: scaleY(1); }
  100% { transform: scaleY(0.5); }
}

.pulse-ring {
  position: absolute;
  top: -5px;
  left: -5px;
  right: -5px;
  bottom: -5px;
  border: 2px solid #ff6b6b;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(1.2); opacity: 0; }
}

.chat-container {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 350px;
  height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
}

.message.user .message-content {
  background: #007bff;
  color: white;
}

.message.ai .message-content {
  background: white;
  color: #333;
  border: 1px solid #e9ecef;
}

.message-text {
  line-height: 1.4;
  word-wrap: break-word;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 5px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-10px); }
}

.chat-input {
  padding: 15px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.chat-input .el-input {
  border-radius: 20px;
}

.chat-input .el-input__inner {
  border-radius: 20px 0 0 20px;
}

.chat-input .el-button {
  border-radius: 0 20px 20px 0;
}
</style>